package com.itheima.netty.block;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

import static com.itheima.utils.ByteBufferUtil.debugRead;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: pzj
 * \* Date: 2021/11/10
 * \* Time: 11:22
 * \* Description:  NIO演示阻塞模式
 * \
 */
@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        //使用 nio 来理解阻塞模式
        final ByteBuffer buffer = ByteBuffer.allocate(16);
        //1、创建服务端
        final ServerSocketChannel ssc = ServerSocketChannel.open();

        //2、绑定端口
        ssc.bind(new InetSocketAddress(8080));

        //3、接受客户端的连接  accept
        ArrayList<SocketChannel> channels = new ArrayList<>();
        while (true){
            //socketChannel 用来与客户端通信
            log.debug("connecting...");
            SocketChannel sc = ssc.accept();    //阻塞住
            log.debug("connected...{}",sc);
            channels.add(sc);
            for (SocketChannel channel : channels) {
                //4、接受客户端数据
                log.debug("before read...{}",channel);
                channel.read(buffer);   //从channel中读取出数据，存入buffer中      阻塞住
                buffer.flip();
                debugRead(buffer);
                buffer.clear();
                log.debug("after read...{}",channel);
            }
        }

    }
}